/*******************************************************************************
* File Name          : usart.c
* Author             : Jon Henry
* Version            : 1.0
* Date               : 5/13/2013
* Description        : USART driver file
*
* HISTORY:
* Date               |	Modification                    |	Author

*******************************************************************************/

/* Includes ------------------------------------------------------------------*/
#include <stm32f4xx_usart.h>
#include <string.h>
#include "minimu_v2.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
char TmtString[60];
/* Private function prototypes -----------------------------------------------*/

void USART6_Init()
{
	GPIO_InitTypeDef GPIO_InitStruct;
	USART_InitTypeDef USART_InitStruct;
	NVIC_InitTypeDef NVIC_InitStructure;

	//Enable peripheral clock
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);

	//Enable GPIO clock
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);

	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOC, &GPIO_InitStruct);
	//Enable pins C6 and C7 alternate function
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6);

	//Setup USART6 parameters
	USART_InitStruct.USART_BaudRate = 57600;
	USART_InitStruct.USART_WordLength = USART_WordLength_8b;
	USART_InitStruct.USART_StopBits = USART_StopBits_1;
	USART_InitStruct.USART_Parity = USART_Parity_No;
	USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	USART_Init(USART6, &USART_InitStruct);

	//Enable USART6 interrupt
	USART_ITConfig(USART6, USART_IT_RXNE, ENABLE);

	//Enable NVIC
	NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	//Enable USART6
	USART_Cmd(USART6, ENABLE);
}



void USART_puts(USART_TypeDef* USARTx, volatile char *s)
{
	while(*s)
	{
		// wait until data register is empty
		while( !(USARTx->SR & 0x00000040) );
		USART_SendData(USARTx, *s);
		*s++;
	}
}

void USART_Xmit()
{
	char str[100];

	strcat(str, "$TEL,");
	getOrientationString(str);
	strcat(str, "\r\n");

	USART_puts(USART6, str);
}


